<template>
  <div class="ex">
    <el-card>
      <!-- 查询 -->
      <el-row :gutter="7">
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true"><i class="el-icon-circle-plus-outline"></i>新建
          </el-button>
          <el-button type="primary"><i class="el-icon-refresh-right"></i>刷新</el-button>
        </el-col>
        <el-col :span="5"><label for="">考试名称</label>
          <el-input v-model="query.examName" placeholder="请输入考试名称" class="inp1"></el-input>
        </el-col>
        <el-col :span="5">
          <label for="">考试时长</label>
          <el-input v-model="query.examTimeLimitStart" placeholder="最小值" class="inp2"></el-input> -
          <el-input v-model="query.examTimeLimitEnd" placeholder="最大值" class="inp2"></el-input>
        </el-col>
        <el-col :span="6"><label for="">更新时间</label>
          <!-- <el-date-picker  v-model="query.uptime" type="" format="yyyy-MM-dd HH:mm:ss" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
          </el-date-picker> -->
           <el-date-picker class="inp3"
      v-model="query.uptime"
      value-format="yyyy-MM-dd HH:mm:ss"
      type="datetimerange"
      range-separator="至"
      start-placeholder="开始日期"
      end-placeholder="结束日期">
    </el-date-picker>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="findInfo()"><i class="el-icon-search"></i>查询</el-button>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-table :data="tableData" border stripe>
        <el-table-column type="index" label="序号" width="50px" prop="id"></el-table-column>
        <el-table-column label="名称" prop="examName"></el-table-column>
        <el-table-column label="总分数" prop="examScore"></el-table-column>
        <el-table-column label="创建人" prop="username"></el-table-column>
        <el-table-column label="考试时长（分钟）" prop="examTimeLimit"></el-table-column>
        <el-table-column label="更新时间" prop="updateTime"></el-table-column>
        <el-table-column label="操作" width="250px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row)">编辑</el-button>
            <!-- 详情按钮 -->
            <el-button type="warning" size="mini" @click="showDialog(scope.row)">详情</el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域@size-change="handleSizeChange" @current-change="handleCurrentChange" -->
      <el-pagination :current-page="page" :page-sizes="[2, 4, 8, 10]" :page-size="num" layout="total, sizes, prev, pager, next, jumper" :total="total" @current-change="getCurrentPage" @size-change="getPageSize">
      </el-pagination>
    </el-card>

    <!-- 新建的对话框 -->
    <el-dialog title="添加考试题目" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
      <el-steps :space="600" :active="activeIndex-0" finish-status="success" align-center>
        <el-step title="考试描述"></el-step>
        <el-step title="选择题目"></el-step>
      </el-steps>
      <!-- 内容主体区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" v-show="activeIndex=='0'">
        <el-form-item label="考试名称" prop="examName">
          <el-input v-model="addForm.examName"></el-input>
        </el-form-item>
        <el-form-item label="考试限时" prop="examTimeLimit">
          <el-input-number v-model="addForm.examTimeLimit" controls-position="right"></el-input-number>
          <!-- <el-input v-model="addForm.number"></el-input> -->
        </el-form-item>
        <el-form-item label="考试简述" prop="examDescription">
          <el-input v-model="addForm.examDescription"></el-input>
        </el-form-item>
        <el-form-item label="班级" prop="examClass">
          <el-select v-model="addForm.examClass" placeholder="请选择班级">
            <el-option v-for="(item, index) in option" :key="index" :label="item" :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="考试时间" prop="starttime">
          <el-date-picker v-model="addForm.starttime" value-format="yyyy-MM-dd HH:mm:ss" type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <!-- <el-form-item label="考试结束时间" prop="endtime">
          <el-input v-model="addForm.endtime"></el-input>
        </el-form-item> -->
      </el-form>

      <!-- 第二步 -->
      <div v-show="activeIndex=='1'" class="ti">
        <!-- <div> -->
        <el-input v-model="count" placeholder="请输入题目个数" @change="actTable"></el-input>
        <el-select v-model="questionCategory" placeholder="请选择科目类型" @change="searchQuestion">
          <el-option v-for="(item, index) in options" :key="index" :label="item" :value="item">
          </el-option>
        </el-select>
        <!-- </div> -->
        <el-table :data="tableList" border class="ta">
          <el-table-column prop="questionName" label="题目">
            <template slot-scope="scope1">
              <el-select v-model="scope1.row.questionName" placeholder="请选择题目" @change="select1(scope1.row)">
                <el-option v-for="item in tablel" :key="item.questionId" :label="item.questionName" :value="item.questionName">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="questionTypeId" label="题目类型" width="200px">
          </el-table-column>
          <el-table-column prop="score" label="分数" width="250px">
            <template slot-scope="scope2">
              <el-input v-model.number="scope2.row.score" placeholder="" width="100" class="inp5" @change="scoree(scope2.row)"></el-input>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 底部区域 "-->
      <span slot="footer" class="dialog-footer" v-show="activeIndex=='0'">
        <el-button @click="addDialogVisible=false">取 消</el-button>
        <el-button type="primary" @click="addnext">下一步</el-button>
      </span>
      <!-- 下一步 {{number}}-->
      <span slot="footer" class="dialog-footer" v-show="activeIndex=='1'">
        <!-- <span class="span1">总分数:{{number}}</span> -->
        <el-button @click="activeIndex='0'">上一步</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑的对话框 -->
    <el-dialog title="更改考试题目" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
      <!-- 内容主体区域 -->
      <el-form :model="editForm" :rules="addFormRules" ref="editFormRef" label-width="100px">
        <el-form-item label="考试名称" prop="examName">
          <el-input v-model="editForm.examName"></el-input>
        </el-form-item>
        <el-form-item label="考试限时" prop="examTimeLimit">
          <el-input-number v-model="editForm.examTimeLimit" controls-position="right"></el-input-number>
        </el-form-item>
        <el-form-item label="考试简述" prop="examDescription">
          <el-input v-model="editForm.examDescription"></el-input>
        </el-form-item>
        <el-form-item label="班级" prop="examClass">
          <el-select v-model="editForm.examClass" placeholder="请选择班级">
            <el-option v-for="(item, index) in option" :key="index" :label="item" :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="考试时间">
          <el-date-picker v-model="editForm.examStartDate"  type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="开始时间">
          </el-date-picker>
          至 <el-date-picker v-model="editForm.examEndDate" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="结束时间">
          </el-date-picker>
              <!-- <el-date-picker
      v-model="editForm.starttime"
      value-format="yyyy-MM-dd"
      type="datetimerange"
      range-separator="至"
      start-placeholder="开始日期"
      end-placeholder="结束日期">
    </el-date-picker> -->
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible=false">取消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  data () {
    return {
      query: {
        examName: '',
        examTimeLimitStart: '',
        examTimeLimitEnd: '',
        examStartDate: '',
        examEndDate: ''
      },
      tablel: [],
      value2: '',
      page: 1,
      num: 2,
      tableData: [],
      tableList: [],
      total: 0,
      addDialogVisible: false,
      editDialogVisible: false,
      activeIndex: '0',
      addForm: {
        examName: '',
        examTimeLimit: 90,
        examDescription: '',
        examClass: '',
        starttime: [],
        examStartDate: '',
        examEndDate: '',
        username: 'admin'
      },
      editForm: {
        examId: '',
        examName: '',
        examTimeLimit: 90,
        examDescription: '',
        examClass: '',
        starttime: [],
        examStartDate: '',
        examEndDate: ''
      },
      questionCategory: '',
      count: '',
      // options: ['SQL', 'Java基础', 'Java进阶', '框架', 'Linux'],
      options: [],
      option: ['一班', '二班', '三班'],
      addFormRules: {
        examName: [{ required: true, message: '请输入考试名称', trigger: 'blur' }],
        examTimeLimit: [{ required: true, message: '请输入考试时间', trigger: 'blur' }],
        examDescription: [{ required: true, message: '请输入考试简述', trigger: 'blur' }],
        examClass: [{ required: true, message: '请输入考试班级' }],
        starttime: [{ required: true, message: '请输入时间' }]
      },
      obj: {},
      optionss: ['', '单选题', '多选题', '判断题']
      // number: 0
    }
  },
  beforeMount () {
    this.selectExamList()
  },
  // watch:{
  //   obj.score(new,old){
  //     if(new!==old){
  //      this.number=0
  //     }

  //   }
  // },
  // computed: {
  //   totalScore () {
  //     console.log(this.obj)
  //     let number = 0
  //     for (const k in this.obj) {
  //     number += this.obj[k]
  //     }
  //     console.log(number)
  //     return number
  //   }
  // },
  methods: {
    // 分页查询所有
    selectExamList () {
      // console.log(this.$api);
      this.$api.exam.getExamList(this.page, this.num).then((res) => {
        const data = res.data.data.examVos
        if (res.data.code == 200) {
          console.log(data)
          this.tableData = data
          this.total = res.data.data.total
          console.log(this.total)
        }
      })
    },
    scoree (row) {
      console.log(row)
      this.obj[row.questionName] = row.score
      console.log(this.obj)
    },
    select1 (row) {
      // console.log(row, '----')
      // console.log(this.tablel)
      for (let i = 0; i < this.count; i++) {
        for (let j = 0; j < this.tablel.length; j++) {
          if (row.questionName == this.tablel[j].questionName) {
            row.questionId = this.tablel[j].questionId
            row.questionTypeId = this.optionss[this.tablel[j].questionTypeId]
          }
          // console.log(row, '+++')
        }
      }
    },
    // 题目个数
    async actTable () {
      const arr = []
      const obj = {
        questionName: '',
        score: '',
        questionId: '',
        questionTypeId: ''
      }
      for (let i = 0; i < this.count; i++) {
        arr[i] = { ...obj }
      }
      this.tableList = arr
      const result = await this.$api.exam.questionQuestion()
      if (result.status == 200) {
        this.options = result.data
      }
      // console.log(result)
    },
    // 查询题目
    searchQuestion () {
      this.$api.exam.searchQuestion(this.questionCategory).then((res) => {
        const data = res.data
        this.tablel = data
        console.log(this.tablel)
      })
    },
    // 分页
    getCurrentPage (page) {
      this.page = page
      // this.num = num;
      this.selectExamList()
    },
    getPageSize (num) {
      // this.page = page;
      this.num = num
      this.page = 1
      this.selectExamList()
    },
    // 新增下一步
    addnext () {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error('请填写必要的表单项！')
        this.activeIndex = '1'
      })
    },
    // 新增关闭对话框
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
      this.count = ''
      this.questionCategory = ''
    },
    // 新增确认
    async addUser () {
      const form = _.cloneDeep(this.addForm)
      form.examCategory = this.questionCategory
      const arr = []
      const arr1 = []
      let number = 0
      // form.examStartDate = this.addForm.starttime[0].toLocaleDateString().split('/').join('-')
      // form.examEndDate = this.addForm.starttime[1].toLocaleDateString().split('/').join('-')
      form.examStartDate = this.addForm.starttime[0]
      form.examEndDate = this.addForm.starttime[1]
      this.tableList.forEach((item) => {
        console.log(item, '+++')
        arr.push(item.questionId)
        arr1.push(item.score)
        number += item.score
      })
      form.examQuestionIds = arr
      form.examScore = arr1
      form.starttime = undefined
      console.log(this.tableList)
      console.log(form)
      if (number != 100) {
        return this.$message.warning('总分数不为100！！！')
      }
      if (number == 100) {
        const result = await this.$api.exam.addOne(form)
        if (result.status == 200) {
          this.addDialogVisible = false
          this.$message.success('新建题目成功')
          this.selectExamList()
        }
        console.log(result)
      }
    },
    // 编辑关闭对话框
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    // 编辑
    showEditDialog (data) {
      this.editForm = data
      // this.editForm.examStartDate = dayjs(this.editForm.examStartDate).format('YYYY-MM-DD HH:mm:ss')
      // this.editForm.examEndDate = dayjs(this.editForm.examEndDate).format('YYYY-MM-DD HH:mm:ss')
      // this.editForm.starttime = [this.editForm.examStartDate, this.editForm.examEndDate]
      console.log(this.editForm)
      this.editDialogVisible = true
    },
    // 编辑确认
    editUser () {
      // const form = _.cloneDeep(this.editForm)
      const form = {}
      form.examId = this.editForm.examId
      form.examName = this.editForm.examName
      form.examTimeLimit = this.editForm.examTimeLimit
      form.examDescription = this.editForm.examDescription
      form.examClass = this.editForm.examClass
      form.examStartDate = this.editForm.examStartDate
      form.examEndDate = this.editForm.examEndDate
      console.log(form)
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请填写必要的表单项！')
        const result = await this.$api.exam.newOne(form)
        console.log(result)
        if (result.status == 200) {
          this.$message.success('更新成功')
          this.selectExamList()
        } else {
          this.$message.error('更新失败')
        }
        this.editDialogVisible = false
      })
    },
    // 模糊查询
    findInfo () {
      console.log(this.query.uptime)
      if (this.query.uptime) {
        // const updateTime = this.query.uptime[0].toLocaleDateString().split('/').join('-')
        // const updateTimes = this.query.uptime[1].toLocaleDateString().split('/').join('-')
        const updateTime = this.query.uptime[0]
        const updateTimes = this.query.uptime[1]
        console.log(updateTime)
        console.log(updateTimes)
        this.query.uptime = updateTime
        this.query.uptimes = updateTimes
      }
      this.$api.exam.findInfo(this.page, this.num, this.query).then((res) => {
        const data = res.data
        // console.log(data);
        this.tableData = data
      })
    },
    // 更新
    // newOne (data) {
    //   if (this.editForm.starttime) {
    //     const updateTime = this.editForm.starttime[0]
    //       .toLocaleDateString()
    //       .split('/')
    //       .join('-')
    //     const updateTimes = this.editForm.starttime[1]
    //       .toLocaleDateString()
    //       .split('/')
    //       .join('-')
    //     this.editForm.examStartDate = updateTime
    //     this.editForm.examEndDate = updateTimes
    //   }
    //   this.$api.exam.newOne(this.editForm.examId, this.editForm.examName, this.editForm.examTimeLimit, this.editForm.examDescription, this.editForm.examClass, this.editForm.examStartDate, this.editForm.examEndDate)
    //   this.selectExamList()
    // },
    // 删除id
    removeUserById (data) {
      console.log(data)
      this.$confirm('此操作将永久删除 该员工工资信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$api.exam.delInfo(data.examId).then((res) => {
            console.log(res)
            if (res.data == 1) {
              this.selectExamList()
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
            } else {
              this.$message({
                type: 'error',
                message: '删除失败'
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      // this.tableData = data.list;
      // this.total = data.total;
      this.selectExamList()
    },
    // 详情
    async showDialog (row) {
      const result = await this.$api.stuExam.stuexamTopic(row.examId)
      this.$store.commit('SETEXAM', result.data)
      const exam = this.$store.state.exam.Allexam
      let pathName = ''
      console.log(exam)
      for (let i = 0; i < exam.length; i++) {
        if (exam[i].topic.length != 0) {
          pathName = exam[i].path
          break
        }
      }
      this.$router.push({
        name: pathName,
        query: { time: this.form.examTimeLimit },
        params: { id: 1 }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.ex {
  width: 80%;
  box-sizing: border-box;
  margin: 20px auto;
}
.span1 {
  display: inline-block;
  background-color: aqua;
  margin-right: 50px;
}
.el-row {
  display: flex;
  justify-content: center;
  align-content: center;
  margin-bottom: 10px;
}

.el-col {
  .inp1 {
    width: 150px;
  }

  .inp2 {
    width: 80px;
  }

  .inp3 {
    width: 250px;
  }

  .el-button {
    margin-right: 10px;
    margin-top: 5px;
  }
}
.ta {
  .el-select {
    width: 400px;
  }
  .inp5 {
    width: 100px;
  }
}
label {
  margin: 5px;
  display: inline-block;
  width: 80px;
  height: 42px;
  text-align: center;
  line-height: 42px;
}

.ti {
  .el-input {
    width: 200px;
    margin: 20px 20px;
  }
}
</style>
